package com.item.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;
import org.apache.ibatis.type.TypeHandler;

import java.io.IOException;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@MappedTypes(List.class)
public class ArrayTypeHandler implements TypeHandler<List<String>> {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void setParameter(PreparedStatement ps, int i, List<String> parameter, JdbcType jdbcType) throws SQLException {
        try {
            String jsonArrayAsString = objectMapper.writeValueAsString(parameter);
            ps.setString(i, jsonArrayAsString);
        } catch (JsonProcessingException e) {
            throw new SQLException("Failed to convert List to JSON string", e);
        }
    }

    @Override
    public List<String> getResult(ResultSet rs, String columnName) throws SQLException {
        String jsonArrayAsString = rs.getString(columnName);
        return parseJsonArray(jsonArrayAsString);
    }

    @Override
    public List<String> getResult(ResultSet rs, int columnIndex) throws SQLException {
        String jsonArrayAsString = rs.getString(columnIndex);
        return parseJsonArray(jsonArrayAsString);
    }

    @Override
    public List<String> getResult(CallableStatement cs, int columnIndex) throws SQLException {
        String jsonArrayAsString = cs.getString(columnIndex);
        return parseJsonArray(jsonArrayAsString);
    }

    private List<String> parseJsonArray(String jsonArrayAsString) throws SQLException {
        try {
            return objectMapper.readValue(jsonArrayAsString, new TypeReference<List<String>>() {});
        } catch (IOException e) {
            throw new SQLException("Failed to parse JSON array", e);
        }
    }
}
